package edu.gmu.project.swe.project;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

import edu.gmu.project.swe.MsgCode;

public class MyServer {
	private static BufferedInputStream bis;
	private static FileInputStream fis;
	private static BufferedOutputStream bout;
	private static FileOutputStream fos;
	private static InputStream is;
	private static OutputStream os;
	private static ServerSocket serverSocket;

	/**
	 * @param args
	 *            the command line arguments
	 */
	public static void main(String[] args) throws IOException {

		try {
			serverSocket = new ServerSocket(4444);
			Socket clientSocket = serverSocket.accept();
			os = clientSocket.getOutputStream();
			is = clientSocket.getInputStream();
			PrintWriter out = new PrintWriter(os, true);
			BufferedReader in = new BufferedReader(new InputStreamReader(is));
			bout = new BufferedOutputStream(clientSocket.getOutputStream());

			String inputLine, outputLine = null;

			// Initiate conversation with client
			// KnockKnockProtocol kkp = new KnockKnockProtocol();
			// outputLine = kkp.processInput(null);
			// out.println(outputLine);

			while ((inputLine = in.readLine()) != null) {
				System.out.println(inputLine);
				if (inputLine.contains("1")) {

					outputLine = "2-pptslides.ppt:307,test.ppt:291";
					out.println(outputLine);
					System.out.println(outputLine);

				} else if (inputLine.contains("2")) {
					String[] response = inputLine.split("-");
					// Obtain the total file size
					long clientFileTotal = Long.getLong(response[2]);
					// Check if this file exists locally
					File f = new File("ServerHome/" + response[1]);

					long remainingOffset = 0;
					if (f.exists()) {
						// Grab the local file's full length
						long total = f.length();
						// Multiply the client's offset by 1024
						clientFileTotal = clientFileTotal * 1024;
						// Subtract the difference and divide by 1024 to respond
						// with the
						// offset where we want to continue getting data
						remainingOffset = (total - clientFileTotal) / 1024;
					}
					String msg = MsgCode.POINTER + ":" + f + ":"
							+ String.valueOf(remainingOffset);
					out.write(msg);
					out.flush();

					try {
						// Open up the file and append if it does exist.
						fos = new FileOutputStream("ServerHome/TEST"
								+ "pptslides.ppt", true);
						bout = new BufferedOutputStream(fos);

					} catch (FileNotFoundException ex) {
						System.out.println("File not found. ");
					}

					byte[] bytes = new byte[(int) 1024];

					int count;
					int myOffset = 0;
					// Read the client's bytes
					while ((count = is.read(bytes)) > 0) {
						// If my offset is up to where we left off, start
						// appending
						// to the existing file
						if (myOffset >= remainingOffset)
							bout.write(bytes, 0, count);
						myOffset++;
					}
					fos.flush();
					bout.flush();
					fos.close();
					bout.close();
				} else if (inputLine.contains("3")) {
//					System.out.println(inputLine);
					File file = new File("ServerHome/pptslides.ppt");
					// Get the size of the file
					byte[] bytes = new byte[(int) 1024];
					fis = new FileInputStream(file);
					bis = new BufferedInputStream(fis);

					int count;
					int offset = 0;
					while ((count = bis.read(bytes)) > 0) {

						bout.write(bytes, 0, count);
						System.out.println(count);
						offset++;
					}
					bout.write(null, 0, 0);
					System.out.println(offset);
					System.out.println(offset * 1024);
					System.out.println(file.length());
					bout.flush();
					fis.close();
					bis.close();
//					bout.close();

				} else if (inputLine.contains("4")) {
					break;
				}
				//
				// if (outputLine.contains("3"))
				// break;
			}

			clientSocket.close();
			out.close();
			in.close();

		} catch (IOException e) {
			System.out
					.println("Exception caught when trying to listen on port "
							+ 4444 + " or listening for a connection");
			System.out.println(e.getMessage());
		}

	}
}
